const http = require('http')
const fs = require('fs')
const url = require('url')
const mimes = require('./lib/mime')
const { join, extname } = require('path')
const qs=require('querystring')
const rootpath = join(__dirname, 'www')

http.createServer((req, res) => {
    let { pathname, query } = url.parse(req.url, true)
    if (req.method === "POST") {
            if(pathname=='/login'){
                let postData=""
                req.on('data',chunk=>postData+=chunk)
                req.on('end',()=>{
                    console.log(qs.parse(postData));
                    res.end('ok')
                })
            }
    } else {
        if (req.url !== './favicon.ico') {
            pathname = pathname === '/' ? './index.html' : pathname
            let filepath = join(rootpath, pathname)
            if (fs.existsSync(filepath)) {
                const ext = extname(filepath).slice(1)
                const mime = mimes[ext]
                res.setHeader('content-type', mime)
                let html

                if ('html' === ext) {
                    console.log(query)

                    html = fs.readFileSync(filepath, 'utf-8')
                    html = html.replace(/\{\{\s*(\w+)\s*\}\}/g, function (preg, match) {
                        return query[match]
                    })
                } else {
                    html = fs.readFileSync(filepath)
                }
                res.end(html)
            } else {
                res.statusCode = 404
                res.end(fs.readFileSync(errpath))
            }
        }
    }

}).listen(3000, '0.0.0.0')